package com.jic.market.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.entity.GoodsSku;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionGiftItemEntity;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.enums.PromotionStatusEnum;
import com.jic.market.mapper.PromotionEntityMapper;
import com.jic.market.mapper.PromotionGiftItemEntityMapper;
import com.jic.market.mapper.PromotionRuleEntityMapper;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.orm.Pagination;
import com.jic.market.request.PromotionGiftItemBatchRequest;
import com.jic.market.request.PromotionGiftItemRequest;
import com.jic.market.response.PageResponse;
import com.jic.market.response.PromotionGiftItemResponse;
import com.jic.market.service.PromotionGiftItemService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * description: PromotionGiftItemServiceImpl
 * date: 2020/3/2 14:48
 * author: wangys
 * version: 1.0
 */
@Service
public class PromotionGiftItemServiceImpl implements PromotionGiftItemService {
    @Autowired
    PromotionGiftItemEntityMapper promotionGiftItemEntityMapper;
    @Autowired
    private CouponConfigMapper couponConfigMapper;

    @Autowired
    private PromotionEntityMapper promotionEntityMapper;
    @Autowired
    private BaseActivityMapper baseActivityMapper;
    @Autowired
    private PromotionRuleEntityMapper promotionRuleEntityMapper;

    @Resource
    private ProductListApi productListApi;
    @Override
    public Integer saveBatch(PromotionGiftItemBatchRequest request) {
        request.getList().stream().forEach(x->{
            PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
            BeanUtils.copyProperties(x, entity);
            entity.setCreator(request.getAdminOperate().getOperator());
            entity.setCreatorName(request.getAdminOperate().getOperateName());
            entity.setUpdator(request.getAdminOperate().getOperator());
            entity.setUpdatorName(request.getAdminOperate().getOperateName());
            if(entity.getGiftNum() == null){
                entity.setGiftNum(1L);
            }
            PromotionGiftItemEntity param = new PromotionGiftItemEntity();
            param.setPromotionRuleId(x.getPromotionRuleId());
            param.setPromotionId(x.getPromotionId());
            param.setDeleteFlag(0);
            param.setGiftType(x.getGiftType());
            //判断是否已经存在
            if(x.getGiftType() == 1){//商品
                param.setMmpId(x.getMmpId());
                param.setMpCode(x.getMpCode());
            }else if(x.getGiftType() == 4 || x.getGiftType() == 5){//优惠券
                param.setCouponId(x.getCouponId());
            }else {
                return;
            }
            List<PromotionGiftItemEntity> list = promotionGiftItemEntityMapper.findAll(param);
            if(CollectionUtils.isNotEmpty(list)){
                list.forEach(i->{
                    entity.setId(i.getId());
                    promotionGiftItemEntityMapper.update(entity);
                });
            }else{
                promotionGiftItemEntityMapper.insert(entity);
            }
        });
        return request.getList().size();
    }

    @Override
    public PromotionGiftItemResponse detail(PromotionGiftItemRequest request) {
        PromotionGiftItemResponse response = new PromotionGiftItemResponse();
        PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
        entity.setId(request.getId());
        PromotionGiftItemEntity query = promotionGiftItemEntityMapper.query(entity);
        BeanUtils.copyProperties(query, response);
        return response;
    }

    @Override
    public List<PromotionGiftItemResponse> findAll(PromotionGiftItemRequest request) {
        PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
        BeanUtils.copyProperties(request, entity);
        entity.setUpdatorName(null);
        entity.setCreatorName(null);
        entity.setDeleteFlag(0);
        List<PromotionGiftItemEntity> all = promotionGiftItemEntityMapper.findAll(entity);
        List<PromotionGiftItemResponse> collect = all.stream().map(x -> {
            PromotionGiftItemResponse response = new PromotionGiftItemResponse();
            BeanUtils.copyProperties(x, response);
            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(x.getCouponId());
            if(couponConfig != null){
                response.setCouponName(x.getMpName());
                response.setCouponUseStartTime(couponConfig.getCouponUseStartTime());
                response.setCouponUseEndTime(couponConfig.getCouponUseEndTime());
                response.setGrantTotalNum(couponConfig.getGrantTotalNum());
                response.setGrantNum(couponConfig.getGrantNum());
                response.setCouponUseDesc(couponConfig.getCouponUseDesc());
                response.setCouponAmount(couponConfig.getCouponAmount());
                response.setUseTotalAmountLimit(couponConfig.getUseTotalAmountLimit());
            }
            if(x.getGiftType() == 1){
//                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(x.getGiftRef());
                List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(x.getGiftRef());
                }});
                ProductStoreInfo goodsSku = productStoreInfos.get(0);
                response.setStock(goodsSku == null ? null : goodsSku.getAvailableStock());
                response.setGoodsCategory(goodsSku == null ? null : goodsSku.getCategoryName());
                response.setSalePrice(goodsSku == null ? null : goodsSku.getSalePriceWithTax());

            }
            return response;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Integer deleteBatch(PromotionGiftItemBatchRequest request) {
        request.getIds().forEach(x->{
            promotionGiftItemEntityMapper.delete(x);
        });
        return request.getIds().size();
    }

    @Override
    public Integer deleteById(PromotionGiftItemRequest request) {
        PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
        entity.setId(request.getId());
        entity.setDeleteFlag(1);
        return promotionGiftItemEntityMapper.update(entity);
    }

    @Override
    public PageResponse<PromotionGiftItemResponse> listByPage(PromotionGiftItemRequest request) {
        PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
        BeanUtils.copyProperties(request, entity);
        if(StringUtils.isEmpty(request.getMpCode())){
            entity.setMpCode(null);
        }
        if(StringUtils.isEmpty(request.getMpName())){
            entity.setMpName(null);
        }
        entity.setUpdatorName(null);
        entity.setCreatorName(null);
        entity.setCreator(null);
        entity.setUpdator(null);
        entity.setDeleteFlag(0);
        Pagination pagination = Pagination.build(request.getStart(), request.getLimit());
        List<PromotionGiftItemEntity> all = promotionGiftItemEntityMapper.findOfPage(entity, pagination);
        int count = promotionGiftItemEntityMapper.countOfPage(entity);
        PageResponse<PromotionGiftItemResponse> pageResponse = new PageResponse<PromotionGiftItemResponse>()
                .setPageNo(request.getStart())
                .setPageSize(request.getLimit())
                .setTotal(count)
                .setRows(
                        all.stream().map(x->{
                            PromotionGiftItemResponse response = new PromotionGiftItemResponse();
                            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(x.getCouponId());
                            if(couponConfig != null){
                                response.setCouponName(x.getMpName());
                                response.setCouponUseStartTime(couponConfig.getCouponUseStartTime());
                                response.setCouponUseEndTime(couponConfig.getCouponUseEndTime());
                                response.setGrantTotalNum(couponConfig.getGrantTotalNum());
                                response.setGrantNum(couponConfig.getGrantNum());
                                response.setCouponUseDesc(couponConfig.getCouponUseDesc());
                                response.setCouponAmount(couponConfig.getCouponAmount());
                                response.setUseTotalAmountLimit(couponConfig.getUseTotalAmountLimit());
                            }
                            //获取优惠券基本信息
                            if(x.getGiftType() == 1){
//                                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(x.getGiftRef());
                                List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                                    setId(x.getGiftRef());
                                }});
                                ProductStoreInfo goodsSku = productStoreInfos.get(0);
                                response.setStock(goodsSku == null ? null : goodsSku.getAvailableStock());
                                response.setGoodsCategory(goodsSku == null ? null : goodsSku.getCategoryName());
                                response.setSalePrice(goodsSku == null ? null : goodsSku.getSalePriceWithTax());

                            }
                            BeanUtils.copyProperties(x, response);
                            return response;
                        }).collect(Collectors.toList())
                );
        return pageResponse;
    }

    @Override
    public Integer update(PromotionGiftItemRequest request) {
        PromotionGiftItemEntity entity = new PromotionGiftItemEntity();
        BeanUtils.copyProperties(request, entity);
        if(entity.getGiftNum() == null){
            entity.setGiftNum(1L);
        }
        return promotionGiftItemEntityMapper.update(entity);
    }

    @Override
    public Integer countByPromotionId(PromotionGiftItemRequest request) {
        AtomicInteger count = new AtomicInteger();
        //查询rules
        PromotionRuleEntity ruleEntity = new PromotionRuleEntity();
        ruleEntity.setPromotionId(request.getPromotionId());
        ruleEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        List<PromotionRuleEntity> ruleEntities = promotionRuleEntityMapper.findAll(ruleEntity);
        ruleEntities.stream().forEach(x->{
            PromotionGiftItemEntity giftItemEntity = new PromotionGiftItemEntity();
            giftItemEntity.setPromotionId(request.getPromotionId());
            giftItemEntity.setPromotionRuleId(x.getId());
            giftItemEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            count.addAndGet(promotionGiftItemEntityMapper.countOfPage(giftItemEntity));
        });
//        PromotionGiftItemEntity giftItemEntity = new PromotionGiftItemEntity();
//        giftItemEntity.setPromotionId(request.getPromotionId());
//        giftItemEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        return count.get();
    }

    @Override
    public String checkTimeliness(PromotionGiftItemRequest request) {
        String msg = null;
        final ImmutableMap<Integer, String> giftTypeMap = ImmutableMap.of(1,"赠品", 2,"优惠券", 3,"红包");
        final ImmutableMap<Integer, Integer> giftTypeConvertMap = ImmutableMap.of(1,1, 2,4, 3,5);

        //获取活动基本信息
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(request.getPromotionId());
        //查询有效ruleId
        PromotionRuleEntity ruleEntity = new PromotionRuleEntity();
        ruleEntity.setPromotionId(request.getPromotionId());
        ruleEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        List<PromotionRuleEntity> ruleEntities = promotionRuleEntityMapper.findAll(ruleEntity);

        if(CollectionUtils.isEmpty(ruleEntities)){
            msg = "请添加" + giftTypeMap.get(promotionEntity.getGiftType());
        }

        PromotionGiftItemEntity giftItemEntity = new PromotionGiftItemEntity();
        giftItemEntity.setGiftType(giftTypeConvertMap.get(promotionEntity.getGiftType()));
        giftItemEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        giftItemEntity.setPromotionId(request.getPromotionId());
        giftItemEntity.setRuleIds(ruleEntities.stream().map(PromotionRuleEntity::getId).collect(Collectors.toList()));
        List<PromotionGiftItemEntity> giftItemEntities = promotionGiftItemEntityMapper.findAll(giftItemEntity);

        if(CollectionUtils.isEmpty(giftItemEntities)){
            msg = "请添加" + giftTypeMap.get(promotionEntity.getGiftType());
        }else{
            if(promotionEntity.getGiftType() != 1){
                List<String> collect = giftItemEntities.stream().filter(g -> {
                    CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(g.getCouponId());
                    BaseActivity baseActivity = baseActivityMapper.queryByPromotionId(g.getCouponId());
                    return !baseActivity.getStatus().equals(PromotionStatusEnum.AUDIT_PASS.getCode() + "") || System.currentTimeMillis() > couponConfig.getCouponUseEndTime().getTime();
                }).map(PromotionGiftItemEntity::getMpName).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(collect)){
                    msg = Joiner.on(";").join(collect);
                    msg = msg + "  " + giftTypeMap.get(promotionEntity.getGiftType()) + "已结束";
                }
            }
        }

        return msg;
    }
}
